package com.javaee.ejb.session;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.javaee.ejb.session.remote.EmployeeManagerRemote;
import com.javaee.ejb.entity.Employee;

/**
 * Session Bean implementation class EmployeeManager
 */
@Stateless
public class EmployeeManager implements EmployeeManagerRemote {

	@PersistenceContext
	private EntityManager entityManager;

	public EmployeeManager() {
	}

	public int saveEmployee(Employee employee) {
		entityManager.persist(employee);
		return employee.getId();
	}

	public Employee getById(int id) {
		return entityManager.find(Employee.class, id);
	}

	public Employee getByUserName(String userName) {
		Query query = entityManager
				.createQuery("FROM Employee employee WHERE employee.userName = :userName");
		query.setParameter("userName", userName);

		try {
			return (Employee) query.getSingleResult();
		} catch (Exception e) {
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	public List<Employee> getListNotAdmin() {
		Query query = entityManager
				.createQuery("FROM Employee employee WHERE employee.isAdmin = :isAdmin");
		query.setParameter("isAdmin", false);

		return (List<Employee>) query.getResultList();
	}

	@SuppressWarnings("unchecked")
	public List<Employee> getListByProjectId(int projectId) {
		Query query = entityManager
				.createQuery("SELECT DISTINCT members FROM Project project INNER JOIN project.members members WHERE project.id = :projectId");
		query.setParameter("projectId", projectId);
		return (List<Employee>) query.getResultList();
	}

	@SuppressWarnings("unchecked")
	public List<Employee> getListNotInProject(int projectId) {
		Query query = entityManager
				.createQuery("SELECT DISTINCT employee FROM Employee employee WHERE employee.isAdmin = :isAdmin AND employee NOT IN (SELECT members FROM Project project INNER JOIN project.members members WHERE project.id = :projectId)");
		query.setParameter("projectId", projectId);
		query.setParameter("isAdmin", false);

		return (List<Employee>) query.getResultList();
	}

}
